<template>
  <div class="dialog">
    <el-dialog :title="'转分塘记录' + titleText" :visible.sync="showDialog" width="55%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="当前批次:" prop="sourceProductionBatchId" class="w50p">
          <el-select filterable clearable v-model="formData.sourceProductionBatchId" filterable clearable @change="batchChange">
            <el-option v-for="(item, index) in batchList" :key="index"
              :label="`${item.mnecode}_${item.varietyName}`"
              :value="item.productionBatchId"
              :disabled="!item.num || (formData.targetProductionBatchId == item.productionBatchId)" />
          </el-select>
        </el-form-item>
        <el-form-item label="转后批次:" prop="targetProductionBatchId" class="w50p">
          <el-select filterable clearable v-model="formData.targetProductionBatchId" filterable clearable @change="batchChangeTarget">
            <el-option v-for="(item, index) in batchList" :key="index"
              :label="`${item.mnecode}_${item.varietyName}`"
              :value="item.productionBatchId" :disabled="(formData.sourceProductionBatchId == item.productionBatchId)" />
          </el-select>
        </el-form-item>
        <el-form-item label="转塘操作人:" prop="staffName" class="w50p">
          <!-- <el-input v-if="formData.staffName" v-model="formData.staffName" clearable placeholder="请选择" /> -->
          <el-select filterable clearable disabled v-model="formData.staffName" filterable clearable placeholder="请选择">
            <el-option v-for="(item, index) in staffList" :key="index" :label="item.staffName" :value="item.staffName" />
          </el-select>
        </el-form-item>
        <el-form-item label="转塘日期:" prop="recordDate" class="w50p">
          <el-date-picker v-model="formData.recordDate" type="datetime" placeholder="选择日期" @change="changeTime"
            value-format="yyyy-MM-dd HH:mm:ss" clearable :picker-options="pickerOptions" />
        </el-form-item>
        <el-row :gutter="15">
          <el-table :data="formData.transferSeparatePondDetailList" tooltip-effect="dark" highlight-current-row
            :row-style="{ height: '80px' }" border stripe class="rightTableData">
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column label="转入鱼类型" prop="fishType" align="center">
              <template slot-scope="scope">
                <el-form-item :prop="'transferSeparatePondDetailList.' + scope.$index + '.fishType'" class="w100p"
                  :rules="{ required: true, message: '鱼类型不能为空', trigger: 'blur' }">
                  <el-select filterable clearable v-model="scope.row.fishType" filterable clearable style="height: 20px;">
                    <el-option v-for="(item, index) in FishType" :key="index" :label="item.value" :value="item.name" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="规格" prop="fishType" align="center">
              <template slot-scope="scope">
                <el-form-item :prop="'transferSeparatePondDetailList.' + scope.$index + '.specificationId'" class="w100p"
                  :rules="{ required: true, message: '规格不能为空', trigger: 'blur' }">
                  <el-select filterable clearable v-model="scope.row.specificationId" filterable clearable placeholder="请先选择当前批次">
                    <el-option v-for="(item, index) in specificationList" :key="index" :label="item.specificationName"
                      :value="item.specificationId" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="转入数量" prop="amount" min-width="95">
              <template slot-scope="scope">
                <el-form-item :prop="'transferSeparatePondDetailList.' + scope.$index + '.num'" class="w100p"
                  :rules="{ required: true, message: '请输入转入数量', trigger: 'blur' }">
                  <el-input v-model="scope.row.num" type="number" min="0"
                    @change="() => { scope.row.num < 0 ? scope.row.num = 0 : '' }">
                    <template slot="append">尾</template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="转入重量" prop="weight" min-width="95">
              <template slot-scope="scope">
                <el-form-item :prop="'transferSeparatePondDetailList.' + scope.$index + '.weight'" class="w100p"
                  :rules="{ required: true, message: '请输入转入重量', trigger: 'blur' }">
                  <el-input v-model="scope.row.weight" type="number" min="0"
                    @change="() => { scope.row.weight < 0 ? scope.row.weight = 0 : '' }">
                    <template slot="append">斤</template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="80">
              <template slot-scope="scope">
                <el-button v-if="nowChanceStau === 'edit'" type="text" style="color:red;text-decoration: underline;"
                  size="small" @click.native.prevent="editRow(scope.row, scope.$index)">{{
                    scope.row.transferSeparatePondDetailId ? '修改' : '添加' }}</el-button>
                <el-button v-if="nowChanceStau === 'edit' && !scope.row.transferSeparatePondDetailId" type="text"
                  style="color:red;text-decoration: underline;" size="small"
                  @click.native.prevent="deleteRow(scope.row, scope.$index)">删除</el-button>
                <el-button v-if="nowChanceStau === 'add'" type="text" style="color:red;text-decoration: underline;"
                  size="small" :disabled="formData.transferSeparatePondDetailList.length <= 1"
                  @click.native.prevent="deleteRow(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
            <template slot="empty">
              <div>请添加数据</div>
            </template>
          </el-table>
        </el-row>
        <el-row :gutter="15">
          <el-button type="info" plain icon="el-icon-circle-plus-outline" class="addInfo"
            @click="addButInfo">添加</el-button>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import specificationApi from "@/api/basic-info-manage/specification"
import BatchMangeApi from "@/api/batch-mange"
import EnumApi from "@/api/enum"
import TransferSeparatePondApi from "@/api/batch-mange/transfer-separate-pond"
import { dialogMixin } from "@/utils/dialogMixin";
import StaffApi from "@/api/basic-info-manage/staff";
let maxTime = null
export default {
  name: '',
  components: {},
  mixins: [dialogMixin],
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      rightTableData: [],
      rules: {
        targetProductionBatchId: [
          { required: true, message: "请选择当前批次", trigger: ["change", "blur"] }
        ],
        sourceProductionBatchId: [
          { required: true, message: "请选择转后批次", trigger: ["change", "blur"] }
        ],
      },
      formData: {},
      breedTypeList: [
        {
          typeName: "吊水养殖",
          typeCode: "HANGING_BREED",
        },
        {
          typeName: "传统养殖",
          typeCode: "TRADITIONAL_BREED",
        },
      ],//养殖类型
      batchList: [],//批次
      specificationList: [],//规格
      FishType: [],
      staffList: [],
      showDialog: this.show,
      buildDateTime1: '',
      buildDateTime2: '',
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime))) || time.getTime() > new Date().getTime();
        },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            if (maxTime < date.getTime() - 3600 * 1000 * 24) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            if (maxTime < date.getTime() - 3600 * 1000 * 24 * 7) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }],
      }
    };
  },
  computed: {
  },
  watch: {
    show (v) {
      maxTime = null
      this.showDialog = v;
      this.buildDateTime = ''
      this.$refs['ruleForm'] && this.$refs['ruleForm'].clearValidate()
    },
    nowChanceStau (v) {
      if (v === 'add') {
        this.queryBatch()
        this.$nextTick(() => {
          let staffId = sessionStorage.getItem('staffId')
          let staffName = sessionStorage.getItem('staffName')
          let userList = this.staffList.filter(item => {
            return Number(item.staffId) === Number(staffId)
          })
          this.formData = {
            staffName: userList.length == 0 ? this.staffList[0].staffName : staffName,
            staffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
            recordDate: this.formatDateTimeMHS(new Date()),
            transferSeparatePondDetailList: [{}]
          }
          this.$set(this.formData, 'recordDate', this.formatDateTimeMHS(new Date()))
          this.$refs['ruleForm'].resetFields()
        })
      }
      if (v === 'edit') {
        this.formData = this.editObject
        BatchMangeApi.queryByCondition().then(res => {
          this.batchList = res.data;
        })
        this.batchChange(this.formData.sourceProductionBatchId)
        this.queryTransferDetail(this.editObject.transferSeparatePondId)
      }
    }
  },
  created () {
    maxTime = null
  },
  mounted () {
    this.queryEnum()
    this.queryStaff()
  },
  methods: {
    changeTime (time) {
      this.$nextTick(() => {
        this.$forceUpdate()
      })
      // console.log(time)
      // console.log(this.formData.recordDate)
    },
    queryStaff () {
      StaffApi.queryByCondition().then(res => {
        this.staffList = res.data
      })
    },
    queryTransferDetail (e) {
      TransferSeparatePondApi.queryByTransferSeparatePondId({ transferSeparatePondId: e }).then(res => {
        this.formData.transferSeparatePondDetailList = res.data
      })
    },
    //查询可选批次
    queryBatch () {
      BatchMangeApi.queryByCondition({ status: 'UN_COMPLETE' }).then(res => {
        this.batchList = res.data;
      })
    },
    batchChange (e) {
      this.batchList.find(item => {
        if (item.productionBatchId === e) {
          this.buildDateTime1 = new Date(item.buildDateTime)
          if (new Date(this.buildDateTime1).getTime(new Date(this.buildDateTime1)) > new Date(this.buildDateTime2).getTime(new Date(this.buildDateTime2))) {
            maxTime = new Date(this.buildDateTime1)
          } else {
            maxTime = this.buildDateTime2 ? new Date(this.buildDateTime2) : new Date(this.buildDateTime1)
          }
          this.formData.recordDate = this.formatDateTimeMHS(maxTime)
          this.$nextTick(() => {
            this.$forceUpdate()
          })
          // if (new Date(item.buildDateTime).getTime(new Date(item.buildDateTime)) > new Date(maxTime).getTime(new Date(maxTime))) {
          //   maxTime = new Date(item.buildDateTime)
          // }
          this.buildDateTime = item.buildDateTime
          specificationApi.queryByCondition({ fishVarietyId: item.fishVarietyId }).then(res => {
            this.specificationList = res.data;
          })
          return true
        }
      })
    },

    batchChangeTarget (e) {
      this.batchList.find(item => {
        if (item.productionBatchId === e) {
          this.buildDateTime2 = new Date(item.buildDateTime)
          if (new Date(this.buildDateTime1).getTime(new Date(this.buildDateTime1)) > new Date(this.buildDateTime2).getTime(new Date(this.buildDateTime2))) {
            maxTime = this.buildDateTime1 ? new Date(this.buildDateTime1) : new Date(this.buildDateTime2)
          } else {
            maxTime = new Date(this.buildDateTime2)
          }
          // this.formData.recordDate = this.formatDateTimeMHS(maxTime)
          this.$nextTick(() => {
            this.$forceUpdate()
          })
          return true
        }
      })
    },
    //查询鱼状态枚举
    queryEnum () {
      EnumApi.list({ enumType: 'FishType' }).then(res => {
        // this.FishType = res.data;
        this.FishType = res.data.filter(function (item) {
          if (item.name !== 'DEAD_FISH') return item;
        });
      })
    },
    // 修改/新增一行数据
    editRow (rows, index) {
      const valiSome = ['transferSeparatePondDetailList.' + index + '.fishType',
      'transferSeparatePondDetailList.' + index + '.specificationId',
      'transferSeparatePondDetailList.' + index + '.num',
      'transferSeparatePondDetailList.' + index + '.weight']

      this.$refs['ruleForm'].validateField(valiSome);// 校验当前修改/添加行

      if (rows.transferSeparatePondDetailId) {
        let params = {
          transferSeparatePondDetailId: rows.transferSeparatePondDetailId,
          fishType: rows.fishType,
          specificationId: rows.specificationId,
          num: rows.num,
          weight: rows.weight,
        }
        TransferSeparatePondApi.detailEdit(params).then(res => {
          if (res.success === true) {
            this.$message.success("修改成功！");
          } else {
            this.$message.error(res.message);
          }
        })
      } else {
        let params = {
          transferSeparatePondId: this.editObject.transferSeparatePondId,
          fishType: rows.fishType,
          specificationId: rows.specificationId,
          num: rows.num,
          weight: rows.weight,
        }
        TransferSeparatePondApi.detailAdd(params).then(res => {
          if (res.success === true) {
            this.queryTransferDetail(this.editObject.transferSeparatePondId);
            this.$message.success("添加成功！");
          } else {
            this.$message.error(res.message);
          }
        })
      }
    },
    // 删除改行
    deleteRow (index) {
      this.formData.transferSeparatePondDetailList.splice(index, 1);
    },
    // 点击添加按按钮
    addButInfo () {
      let list = {};
      this.formData.transferSeparatePondDetailList.unshift(list);
    },
    save (formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            TransferSeparatePondApi.edit(this.formData).then(res => {
              if (res.success === true) {
                this.$message.success("修改成功！");
                this.close()
              } else {
                this.$message.error(res.message);
              }
            });
          } else if (this.nowChanceStau === "add") {
            let params = {
              ...this.formData
            }
            TransferSeparatePondApi.add(params).then(res => {
              if (res.success === true) {
                this.$message.success("添加成功！");
                this.close()
              } else if (res.errCode === 200) {
                this.$message.warning(res.message);
                this.close()
              } else {
                this.$message.error("系统错误，请稍后再试");
                this.close()
              }
            }).catch(err => {
              console.log(err)
            });
          }
        } else {
          return false;
        }
      });
    },
    close () {
      this.$emit("closeDialog");
    },
    cancel () {
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped>
.rightTableData {
  ::v-deep .el-form-item__error {
    top: calc(100% - 5px);
  }

  ::v-deep .el-form-item {
    height: 40px;
    margin-bottom: 0;

    .el-input__inner {
      height: 40px;
    }
  }

  ::v-deep .cell {
    overflow: visible;
  }

  // ::v-deep .el-input__inner{

  // }
}

.addInfo {
  width: 100%;
}

::v-deep .el-table {
  position: relative;
}
</style>
